package example;

import entity.Person;
import org.junit.Test;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

/**
 * key必须是同一类的对象
 * 按照添加进的元素key的属性排序
 */
public class TreeMapTest {

    @Test
    public void testComparator() {

        Map<Person, Integer> map = new TreeMap<>(new Comparator<Person>() {

            @Override
            public int compare(Person o1, Person o2) {
                int i = o1.getAge() - o2.getAge();
                if (i == 0) {
                    return o1.getName().compareTo(o2.getName());
                } else {
                    return i;
                }
            }
        });

        map.put(new Person(20,"jj"), 12);
        map.put(new Person(13,"fd"), 12);
        map.put(new Person(13,"fd"), 12);
        System.out.println(map);
    }

    @Test
    public void testComparable() {
        Map<Person, Integer> map = new TreeMap<>();
        map.put(new Person(20,"jj"), 12);
        map.put(new Person(13,"fd"), 12);
        map.put(new Person(14,"fd"), 12);
        System.out.println(map);
    }

}



